package com.epfresh.supplier.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.utils.CommonUtils;
import com.epfresh.supplier.R;
import com.epfresh.supplier.constant.Constant;
import com.epfresh.api.utils.AppUtils;
import com.tencent.mmkv.MMKV;

import java.util.ArrayList;
import java.util.List;

import cn.jpush.android.api.InstrumentedActivity;

/**
 * 欢迎界面 检查更新 检查网络（设置SharedPreferences）
 *
 * @author zzq 启动线程 跳转到 mainActivity
 */
public class WelcomeActivity extends InstrumentedActivity implements ViewPager.OnPageChangeListener,
        View.OnClickListener {

    private Context context;
    private ViewPager viewPager;
    private PagerAdapter pagerAdapter;
    private TextView startButton, tvNow;
    private LinearLayout indicatorLayout;
    private ArrayList<View> views;
    private ImageView[] indicators = null;
    private int[] images;
    SharedPreferences preferences;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CommonUtils.setImmersiveStatusBar(this);
        setContentView(R.layout.activity_welcome);
        ApplicationHelper.isHomeActivityAlive = true;
        context = this;
        preferences = getSharedPreferences(
                Constant.USERINFO, Activity.MODE_PRIVATE);
        String flag = preferences.getString("flag", null);
        if (flag == null) {
            startFirst();
            return;
        }
        //startMainActivity();
        intoHome();
    }

    private void startMainActivity() {
        // 启动MainActivity
        new Thread() {
            public void run() {
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        intoHome();
                    }
                });
            }
        }.start();
    }

    private void intoHome() {
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        int toIndex = MMKV.defaultMMKV().decodeInt("toIndex", -1);
        if (((BaseApplication) getApplication()).getUser().getAccess_token() != null && toIndex != -1) {
            gotoPage(toIndex);
        } else {
            Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
            startActivity(intent);
            finish();
        }
    }

    //判断是进入主页还是进入开店流程中去
    private void gotoPage(int index) {
        if (index == 0) {
            Intent main = new Intent(getApplicationContext(), StoreActivity.class);
            startActivity(main);
            finish();
        } else if (index == 1) {
            Intent main = new Intent(getApplicationContext(), FirstPostAuditActivity.class);
            startActivity(main);
            finish();
        } else {
            Intent main = new Intent(getApplicationContext(), HomeNewActivity.class);
            startActivity(main);
            finish();
        }
    }

    //按钮的点击事件
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.start_Button || v.getId() == R.id.tv_now) {
            Editor editor = preferences.edit();
            editor.putString("flag", "flag");
            editor.putString("uuid", AppUtils.getUniquePsuedoID());
            editor.commit();
            Intent intent = new Intent(getApplicationContext(),
                    LoginActivity.class);
            startActivity(intent);
            finish();
        }
    }

    @Override
    public void onPageScrollStateChanged(int arg0) {
    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
    }

    // 监听viewpage
    @Override
    public void onPageSelected(int arg0) {
        // 显示最后一个图片时显示按钮
        if (arg0 == indicators.length - 1) {
            startButton.setVisibility(View.VISIBLE);
            tvNow.setVisibility(View.INVISIBLE);
        } else {
            tvNow.setVisibility(View.VISIBLE);
            startButton.setVisibility(View.INVISIBLE);
        }
        // 更改指示器图片
        for (int i = 0; i < indicators.length; i++) {
            indicators[arg0].setBackgroundResource(R.mipmap.welcome_point);
            if (arg0 != i) {
                indicators[i].setBackgroundResource(R.mipmap.welcome_point_);
            }
        }
    }

    void startFirst() {
        View firstPanel = ((ViewStub) findViewById(R.id.view_first)).inflate();
        firstPanel.setVisibility(View.VISIBLE);
        images = new int[]{R.mipmap.welcome_01, R.mipmap.welcome_02,
                R.mipmap.welcome_03};
        viewPager = (ViewPager) findViewById(R.id.viewpage);
        startButton = (TextView) findViewById(R.id.start_Button);
        startButton.setOnClickListener(this);
        tvNow = (TextView) findViewById(R.id.tv_now);
        tvNow.setOnClickListener(this);
        indicatorLayout = (LinearLayout) findViewById(R.id.indicator);
        views = new ArrayList<View>();
        indicators = new ImageView[images.length]; // 定义指示器数组大小
        for (int i = 0; i < images.length; i++) {
            // 循环加入图片
            ImageView imageView = new ImageView(context);
            imageView.setBackgroundResource(images[i]);
            views.add(imageView);
            // 循环加入指示器
            indicators[i] = new ImageView(context);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            lp.setMargins(20, 0, 0, 0);
            indicators[i].setLayoutParams(lp);
            indicators[i].setBackgroundResource(R.mipmap.welcome_point_);
            if (i == 0) {
                indicators[i].setBackgroundResource(R.mipmap.welcome_point);
            }
            indicatorLayout.addView(indicators[i]);
        }
        pagerAdapter = new BasePagerAdapter(views);
        viewPager.setAdapter(pagerAdapter); // 设置适配器
        viewPager.addOnPageChangeListener(this);
    }

    class BasePagerAdapter extends PagerAdapter {
        private List<View> views = new ArrayList<View>();

        public BasePagerAdapter(List<View> views) {
            this.views = views;
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public int getCount() {
            return views.size();
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(views.get(position));
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(views.get(position));
            return views.get(position);
        }
    }
}
